package com.ljfiction.book.activitys;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.AddBookBean;
import com.ljfiction.book.Dialog.BookClassifydialog;
import com.ljfiction.book.Dialog.Booktabledialog;
import com.ljfiction.book.Dialog.ImageDialog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.Dialog.TishiCreatchapterDialog;
import com.ljfiction.book.MyView.ContainsEmojiEditText;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.EventTool;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.rey.material.app.BottomSheetDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class WriterActivity extends BaseActivity {

    @BindView(R.id.daohanglan_addwrighter)
    LinearLayout daohanglanAddwrighter;
    @BindView(R.id.back_addWriter)
    ImageView backAddWriter;
    @BindView(R.id.bookName_addbook)
    ContainsEmojiEditText bookNameAddbook;
    @BindView(R.id.bookimage_addbook)
    ImageView bookimageAddbook;
    @BindView(R.id.category)
    EditText category;
    @BindView(R.id.worklabel)
    EditText worklabel;
    @BindView(R.id.shoufa_addbook)
    CheckBox shoufaAddbook;
    @BindView(R.id.shouquan_addbook)
    CheckBox shouquanAddbook;
    @BindView(R.id.tijiao_addbook)
    SuperButton tijiaoAddbook;
    @BindView(R.id.description_addbook)
    TextView descriptionAddbook;

    //书封面
    private ImageDialog imageDialog;
    private BookClassifydialog bookClassifydialog;//分类

    private Booktabledialog booktabledialog;//情节标签
    private List<AddBookBean.DataBean.BooklablesListBean> lableList = new ArrayList<>();
    private List<AddBookBean.DataBean.ClassificationListBean> classfyList = new ArrayList<>();
    private String lableid = "", classifyid = "";
    private AddBookBean addbookbean;
    private AddBookBean.DataBean adbbd;
    private boolean isImage = false;//是否上传图片
    private String isFirst="1";//1是网站首发，0是授权发布
    private NoBackgLodDialog noBackgLodDialog;
    private TishiCreatchapterDialog tishdialog;
    private String bookId="17";//创建成功时的书的id

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_writer);
        ButterKnife.bind(this);
        todaohanglanHeight(daohanglanAddwrighter, this);
        intData();
    }

    private void intData() {
        OkHttpUtils.get(HttpManager.IP + "/book-EditBookEcho")

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            addbookbean = gson.fromJson(s, AddBookBean.class);
                            if (200 == addbookbean.getReturnCode()) {
                                adbbd = addbookbean.getData();
                                lableList.clear();
                                classfyList.clear();
                                lableList.addAll(adbbd.getBooklablesList());
                                classfyList.addAll(adbbd.getClassificationList());

                            } else {
                                showToast("网络故障");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        bookNameAddbook.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        bookNameAddbook.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
                //s:变化后的所有字符
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //s:变化前的所有字符； start:字符开始的位置； count:变化前的总字节数；after:变化后的字节数
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //S：变化后的所有字符；start：字符起始的位置；before: 变化之前的总字节数；count:变化后的字节数
                if (!StringTool.verifyBookName(s.toString())){
                    showToast("书名只支持汉字、字母、数字、中文冒号和中文逗号");
                    bookNameAddbook.setText((s.toString()).substring(0,start));
                    bookNameAddbook.setSelection(start);
                }
                if (s.length() >= 20) {
                    showToast("书名不可以超过20字哦");
                }

            }
        });

    }


    @OnClick({R.id.back_addWriter, R.id.bookimage_addbook, R.id.bookName_addbook, R.id.category, R.id.worklabel,  R.id.shoufa_addbook, R.id.shouquan_addbook, R.id.tijiao_addbook,R.id.description_addbook})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_addWriter:
                goBack();
                break;
            case R.id.bookimage_addbook:
                imageDialog = new ImageDialog(this, "logoName.jpg", new ImageDialog.Listener() {
                    @Override
                    public void getImage(Bitmap photo) {
                        bookimageAddbook.setImageBitmap(photo);
                        isImage = true;
                    }
                });
                break;
            case R.id.bookName_addbook:
                break;
            case R.id.category:
                bookClassifydialog = new BookClassifydialog(this, classfyList, new BookClassifydialog.Listener() {
                    @Override
                    public void ok(String str, String id) {
                        category.setText(str);
                        classifyid = id;
                    }
                });
                break;
            case R.id.worklabel:
                booktabledialog = new Booktabledialog(this, lableList, new Booktabledialog.Listener() {
                    @Override
                    public void ok(String str, String id) {
                        worklabel.setText(str);
                        lableid = id;
                    }
                });
                break;
            case R.id.description_addbook:
              Intent  intent=new Intent(WriterActivity.this,EditJianjieActivity.class);
                if (descriptionAddbook.getText().length()>0){
                   intent.putExtra("jianjietext",descriptionAddbook.getText().toString());
                    intent.putExtra("type",3);
                }else {
                    intent.putExtra("type",0);
                }

                startActivityForResult(intent,5);
                break;
            case R.id.shoufa_addbook:
                if (shoufaAddbook.isChecked()) {
                    shouquanAddbook.setChecked(false);
                    isFirst="1";
                }
                break;
            case R.id.shouquan_addbook:
                if (shouquanAddbook.isChecked()) {
                    shoufaAddbook.setChecked(false);
                    isFirst="0";
                }
                break;
            case R.id.tijiao_addbook:
                if (StringTool.isEmpty(bookNameAddbook.getText().toString())) {
                    showToast("请输入书名");
                    return;
                } else if (!StringTool.verifyBookName(bookNameAddbook.getText().toString())) {
                    showToast("书名只支持汉字、字母、数字、中文冒号和中文逗号");
                    return;
                } else if ("".equals(category.getText().toString().trim())) {
                    showToast("请选择分类");
                    return;
                } else if ("".equals(worklabel.getText().toString().trim())) {
                    showToast("请选择标签");
                    return;
                } else if (StringTool.isEmpty(descriptionAddbook.getText().toString())) {
                    showToast("请填写简介");
                    return;
                } else if (!shoufaAddbook.isChecked() && !shouquanAddbook.isChecked()) {
                    showToast("请选择发布方式");
                    return;
                }
                OkHttpUtils.post(HttpManager.IP + "/book-checkName")

                        .params("bookName", bookNameAddbook.getText().toString())
                        .execute(new StringCallback() {
                            @Override
                            public void onBefore(BaseRequest request) {
                                super.onBefore(request);
                                if (noBackgLodDialog==null){
                                    noBackgLodDialog=new NoBackgLodDialog(WriterActivity.this,true);
                                }
                                noBackgLodDialog.show();
                            }

                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(s);
                                    if (jsonObject.getInt("returnCode") == 200) {
                                        creatBook();
                                    } else {
                                        if (noBackgLodDialog!=null){
                                            noBackgLodDialog.dismis();
                                        }
                                        showToast(jsonObject.getString("msg"));
                                    }
                                } catch (Exception e) {
                                    if (noBackgLodDialog!=null){
                                        noBackgLodDialog.dismis();
                                    }
                                    e.printStackTrace();
                                }
                            }
                        });
                break;


        }
    }

    private void creatBookImage(String bookid) {
        OkHttpUtils.post(HttpManager.IP + "/sys-BookCoverAvatarimgUpload")

                .params("bookid", bookid)
                .params("file", new File(getExternalCacheDir() + "/logoName.jpg"))
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismis();
                        }
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {

                            } else {
                                showToast("图片上传失败，请在编辑中修改");
                            }
                            totishiCreatchapter();
                        } catch (JSONException e) {
                            e.printStackTrace();
                            goBack();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }
                });
    }

    private void creatBook() {

        OkHttpUtils.post(HttpManager.IP + "/book-create")

                .params("bookName", bookNameAddbook.getText().toString())
                .params("writerName", UserManageBean.userBean.getPseudonym())
                .params("bookRemarks", UserManageBean.userBean.getUserCode()+"_0")
                .params("bookIntroduction", StringTool.getJianjieText(descriptionAddbook.getText().toString()))
                .params("bookLabId", lableid)
                .params("bookAuthorization", isFirst)
                .params("bookClassificationId", classifyid)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new NoBackgLodDialog(WriterActivity.this,true);
                        }
                        if (!noBackgLodDialog.isShowing()){
                            noBackgLodDialog.show();
                        }
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                showToast(js.getString("msg"));
                                bookId=String.valueOf(js.getInt("data"));
                                if (isImage) {
                                    creatBookImage(bookId);
                                } else {
                                    if (noBackgLodDialog!=null){
                                        noBackgLodDialog.dismis();
                                    }
                                    totishiCreatchapter();
                                }

                            } else {
                                if (js.getInt("returnCode") == 400){
                                    Intent intent=new Intent(WriterActivity.this,LoginActivity.class);
                                    startActivity(intent);
                                }
                                showToast(js.getString("msg"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    private void totishiCreatchapter() {
        if (tishdialog==null){
            tishdialog = new TishiCreatchapterDialog(this);
            tishdialog.setListener(new TishiCreatchapterDialog.Listener() {
                @Override
                public void closeClick() {
                    Intent intent =new Intent(WriterActivity.this,ArticleActivity.class);
                    intent.putExtra("bookId", bookId);
                    intent.putExtra("bookName", bookNameAddbook.getText().toString());
                    intent.putExtra("isCaogao", 0);
                    intent.putExtra("isvip",0);
                  startActivityForResult(intent,10);
                }
            });
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==5&&resultCode==5){
            descriptionAddbook.setText(data.getStringExtra("jianjietext"));
        }else if (resultCode== Activity.RESULT_OK){
            imageDialog.onActivityResult(data, requestCode,0);
        }else if (requestCode==10){
            goBack();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
